package com.match.competition_role.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.match.competition_role.entity.CompetitionPermission;
import com.match.competition_role.entity.CompetitionRole;
import com.match.competition_role.entity.CompetitionRolePermission;
import com.match.competition_role.entity.CompetitionUserRole;
import com.match.competition_role.helper.MemuHelper;
import com.match.competition_role.helper.PermissionHelper;
import com.match.competition_role.mapper.CompetitionPermissionMapper;
import com.match.competition_role.service.CompetitionPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.match.competition_role.service.CompetitionRolePermissionService;
import com.match.competition_role.service.CompetitionRoleService;
import com.match.competition_role.service.CompetitionUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author AdiosF
 * @since 2021-10-08
 */
@Service
public class CompetitionPermissionServiceImpl extends ServiceImpl<CompetitionPermissionMapper, CompetitionPermission> implements CompetitionPermissionService {
    @Autowired
    private CompetitionRolePermissionService competitionRolePermissionService;
    @Autowired
    private CompetitionRoleService competitionRoleService;
    @Autowired
    private CompetitionUserRoleService competitionUserRoleService;

    /**
     * 查询所有权限
     * @return
     */
    @Override
    public List<CompetitionPermission> findAllPermission() {
        //1.查询出所有权限
        QueryWrapper<CompetitionPermission> competitionPermissionQueryWrapper=new QueryWrapper<>();
        competitionPermissionQueryWrapper.orderByDesc("gmt_create");
        List<CompetitionPermission> competitionPermissionList = baseMapper.selectList(competitionPermissionQueryWrapper);
        //2 把查询所有菜单list集合按照要求进行封装
        List<CompetitionPermission> resultList = bulidPermission(competitionPermissionList);
        return resultList;
    }


    //把返回所有菜单list集合进行封装的方法
    public static List<CompetitionPermission> bulidPermission(List<CompetitionPermission> competitionPermissionList) {
        //封装最后返回的集合
        List<CompetitionPermission> finallyList = new ArrayList<>();
            for (CompetitionPermission competitionPermission : competitionPermissionList) {
                //得到顶级目录
                if ("0".equals(competitionPermission.getPid())){
                    //设置顶层菜单的level是1
                    competitionPermission.setLevel(1);
                    competitionPermission.setLabel(competitionPermission.getPermissionName());
                    //根据顶层菜单，向里面进行查询子菜单
                    finallyList.add((selectChildren(competitionPermission,competitionPermissionList)));
                }

        }
        return finallyList;
    }


    private static CompetitionPermission selectChildren(CompetitionPermission competitionPermission, List<CompetitionPermission> competitionPermissionList) {
        //1 因为向一层菜单里面放二层菜单，二层里面还要放三层，把对象初始化
        competitionPermission.setChildren(new ArrayList<CompetitionPermission>());
        //2 遍历所有菜单list集合，进行判断比较，比较id和pid值是否相同
        for (CompetitionPermission permission : competitionPermissionList) {
            //判断 id和pid值是否相同
            if (permission.getPid().equals(competitionPermission.getId())){
                //把父菜单的level值+1
                int level = competitionPermission.getLevel()+1;
                permission.setLevel(level);
                permission.setLabel(permission.getPermissionName());
                //如果children为空，进行初始化操作
                if(competitionPermission.getChildren() == null) {
                    competitionPermission.setChildren(new ArrayList<CompetitionPermission>());
                }
                //把查询出来的子菜单放到父菜单里面
                competitionPermission.getChildren().add(selectChildren(permission,competitionPermissionList));
            }
        }
        return competitionPermission;
    }


    /**
     * 根据权限ID递归删除权限
     * @param permissionId
     * @return
     */
    @Override
    public void deletePermissionById(String permissionId) {
        //1.存储要删除的ID
        List<String> idList=new ArrayList<>();
        //向idList集合设置删除菜单id
        this.selectPermissionChildById(permissionId,idList);
        //把当前id封装到list里面
        idList.add(permissionId);
        //2.到中间表删除所有权限
        List<String> list=new ArrayList<>();
        for (String permissionid : idList) {
            List<CompetitionRolePermission> permissionList = competitionRolePermissionService.list(new QueryWrapper<CompetitionRolePermission>().eq("permission_id", permissionid));
            List<String> collect = permissionList.stream().map(item -> item.getId()).collect(Collectors.toList());
            for (String s : collect) {
                //得到所有的中间表主键ID
                list.add(s);
            }
        }
        if (list.size()>0){
            competitionRolePermissionService.removeByIds(list);
        }
        baseMapper.deleteBatchIds(idList);
    }


    private void selectPermissionChildById(String permissionId, List<String> idList) {
        //得到所有的权限
        QueryWrapper<CompetitionPermission> competitionPermissionQueryWrapper=new QueryWrapper<>();
        competitionPermissionQueryWrapper.eq("pid",permissionId);
        competitionPermissionQueryWrapper.select("id");
        List<CompetitionPermission> competitionPermissionList = baseMapper.selectList(competitionPermissionQueryWrapper);
        //把competitionPermissionList里面菜单id值获取出来，封装idList里面，做递归查询
        competitionPermissionList.stream().forEach(item -> {
            //封装idList里面
            idList.add(item.getId());
            //递归查询
            this.selectPermissionChildById(item.getId(),idList);
        });
    }


    /**
     * 为角色分配权限
     * @param roleId
     * @param permissionId
     */
    @Override
    public void saveRolePermission(String roleId, String[] permissionId) {
        //当角色存在时删除已经存在的角色
        competitionRolePermissionService.remove(new QueryWrapper<CompetitionRolePermission>().eq("role_id",roleId));

        List<CompetitionRolePermission> competitionRolePermissionList =new ArrayList<>();
        for (String s : permissionId) {
            CompetitionRolePermission competitionRolePermission =new CompetitionRolePermission();
            competitionRolePermission.setRoleId(roleId);
            competitionRolePermission.setPermissionId(s);
            competitionRolePermissionList.add(competitionRolePermission);
        }
        //向中间表存储数据
        competitionRolePermissionService.saveBatch(competitionRolePermissionList);
    }


    /**
     * 根据教师职工号获取教师权限
     * @param number
     * @return
     */
    @Override
    public List<String> selectPermissionValueByTeacherNumber(String number) {
        List<String> stringList = baseMapper.selectPermissionValueByTeacherNumber(number);
        return stringList;
    }


    /**
     * 根据用户number获取用户菜单权限
     * @param number
     * @return
     */
    @Override
    public List<JSONObject> selectPermissionByUserNumber(String number) {
        List<CompetitionUserRole> userRoleList = competitionUserRoleService.list(new QueryWrapper<CompetitionUserRole>().eq("user_id", number).select("role_id"));
        List<String> stringroleId=userRoleList.stream().map(item -> item.getRoleId()).collect(Collectors.toList());
        List<String> stringPermissionId=new ArrayList<>();
        //得到角色对应的权限ID
        for (String s : stringroleId) {
            List<CompetitionRolePermission> list = competitionRolePermissionService.list(new QueryWrapper<CompetitionRolePermission>().eq("role_id", s).select("permission_id").orderByAsc("gmt_create"));
            List<String> collect = list.stream().map(item -> item.getPermissionId()).collect(Collectors.toList());
            for (String permissionId : collect) {
                stringPermissionId.add(permissionId);
            }
        }
        List<CompetitionPermission> list = baseMapper.selectBatchIds(stringPermissionId);
        List<CompetitionPermission> permissionList = PermissionHelper.bulid(list);
        List<JSONObject> result = MemuHelper.bulid(permissionList);
        return result;
    }


    @Override
    public CompetitionPermission saveCompetitionPermission(CompetitionPermission competitionPermission) {
        baseMapper.insert(competitionPermission);
        return competitionPermission;
    }

    /**
     * 根据父ID获取子菜单
     * @param id
     * @return
     */
    @Override
    public List<CompetitionPermission> getChildren(String id,Boolean states) {
        List<CompetitionPermission> competitionPermissionList = baseMapper.selectList(null);
        List<CompetitionPermission> list = this.bulidPermission(id,states,competitionPermissionList);
        return list;
    }

    //根据父ID获取子菜单
    public static List<CompetitionPermission> bulidPermission(String Pid,Boolean states,List<CompetitionPermission> competitionPermissionList) {
        //封装最后返回的集合
        List<CompetitionPermission> finallyList = new ArrayList<>();
        for (CompetitionPermission competitionPermission : competitionPermissionList) {
            //得到顶级目录
            if (Pid.equals(competitionPermission.getPid())){
                competitionPermission.setStates(states);
                //根据顶层菜单，向里面进行查询子菜单
                finallyList.add((selectChildren(states,competitionPermission,competitionPermissionList)));
            }

        }
        return finallyList;
    }
    private static CompetitionPermission selectChildren(Boolean states,CompetitionPermission competitionPermission, List<CompetitionPermission> competitionPermissionList) {
        //1 因为向一层菜单里面放二层菜单，二层里面还要放三层，把对象初始化
        competitionPermission.setChildren(new ArrayList<CompetitionPermission>());
        //2 遍历所有菜单list集合，进行判断比较，比较id和pid值是否相同
        for (CompetitionPermission permission : competitionPermissionList) {
            //判断 id和pid值是否相同
            if (permission.getPid().equals(competitionPermission.getId())){
                permission.setStates(states);
                //如果children为空，进行初始化操作
                if(competitionPermission.getChildren() == null) {
                    competitionPermission.setChildren(new ArrayList<CompetitionPermission>());
                }
                //把查询出来的子菜单放到父菜单里面
                competitionPermission.getChildren().add(selectChildren(permission,competitionPermissionList));
            }
        }
        return competitionPermission;
    }


    /**
     * 判断用户是否系统管理员
     * @param teacherNumber
     * @return
     */
    private boolean isSysAdmin(String teacherNumber) {
        QueryWrapper<CompetitionUserRole> competitionUserRoleQueryWrapper=new QueryWrapper<>();
        competitionUserRoleQueryWrapper.eq("user_id",teacherNumber);
        CompetitionUserRole one = competitionUserRoleService.getOne(competitionUserRoleQueryWrapper);
        CompetitionRole role = competitionRoleService.getById(one.getRoleId());
        if(null != role && "系统管理员".equals(role.getRoleName())) {
            return true;
        }
        return false;
    }
}
